package com.han.shadow.customerapp.activity;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.han.shadow.customerapp.R;
import com.han.shadow.customerapp.adapter.MyCartAdapter;
import com.han.shadow.customerapp.bean.Business;
import com.han.shadow.customerapp.bean.Goods;
import com.han.shadow.customerapp.fragment.GoodsInfoFragment;
import com.han.shadow.customerapp.fragment.GoodsListFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class GoodsActivity extends Activity {




    private GoodsInfoFragment goodsInfoFragment = null;
    private GoodsListFragment goodsListFragment = null;

    private FragmentManager fManager;
    private FragmentTransaction fTransaction;


    private Button buttonCart = null;
    private Button buttonCheckout = null;


    private String bID = "";
    private String bName = "";
    private Map<String, Integer> goodsCart = new LinkedHashMap<>();
    private float allPrice = 0;




    private TextView textCartStatus;
    private LinearLayout ll2 = null;


    private PopupWindow popupWindow;
    private ListView listCart;

    private BaseAdapter cartAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods);


        Bundle bundle = getIntent().getExtras();
        bID = bundle.getString("bID");
        bName = bundle.getString("bName");

        initCtrls();
        initFragment();
        initPopCart();
        initCheckoutBtn();

    }


    public void initCtrls() {
        textCartStatus = (TextView) findViewById(R.id.textCartStatus);
        buttonCart = (Button) findViewById(R.id.buttonCart);
        buttonCheckout = (Button) findViewById(R.id.buttonCheckout);
        ll2 = (LinearLayout) findViewById(R.id.gl_ll_2);
    }


    private void initFragment() {
        goodsListFragment = new GoodsListFragment(this, getLayoutInflater(), bID, handler);
        fManager = getFragmentManager();
        fTransaction = fManager.beginTransaction();
        fTransaction.add(R.id.gl_content, goodsListFragment);
        fTransaction.show(goodsListFragment);
        fTransaction.commit();
    }

    private void hideAllFragment() {
        if (goodsListFragment != null) fTransaction.hide(goodsListFragment);

    }


    //更新购物车
    private void updateCart(String id, int c) {
        for (Map.Entry<String, Integer> entry : goodsCart.entrySet()) {
            if (entry.getKey().equals(id)) {
                int num = entry.getValue();
                num += c;
                if (num <= 0) num = 0;
                entry.setValue(num);
            }
        }
        calAllPrice();

    }

    private void calAllPrice() {
        float price = 0;
        List<Goods> goodses = goodsListFragment.getGoodses();
        for (Map.Entry<String, Integer> entry : goodsCart.entrySet()) {
            for (Goods g : goodses) {
                if (g.getGid().equals(entry.getKey())) {
                    price += ((float) g.getPrice() / 10) * entry.getValue();
                }
            }
        }
        allPrice = price;
        textCartStatus.setText("总价:" + allPrice + " 元");
    }


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {//添加购物车
                goodsInfoFragment.dismiss();
                int count = msg.getData().getInt("count");
                if (count > 0) {
                    String gID = msg.getData().getString("gID");
                    goodsCart.put(gID, count);

                    float p = ((float) msg.getData().getInt("price") / 10) * count;
                    allPrice += p;
                    textCartStatus.setText("总价:" + allPrice + " 元");
                }
            } else if (msg.what == 2) {//打开商品信息
                Goods goods = (Goods) msg.getData().getSerializable("goods");
                List<Bitmap> bms = (List<Bitmap>) msg.getData().getSerializable("bitmap");
                goodsInfoFragment = new GoodsInfoFragment(goods,bms, handler);
                fTransaction = fManager.beginTransaction();
                goodsInfoFragment.show(fTransaction, "商品详情");

            } else if (msg.what == 3) {//加
                updateCart(msg.getData().getString("id"), 1);
            } else if (msg.what == 4) {//减
                updateCart(msg.getData().getString("id"), -1);
            } else if (msg.what == 5) {//清空
                if (null != popupWindow) {
                    popupWindow.dismiss();
                    textCartStatus.setText("多选有优惠");
                }
            }
        }
    };



    public void initCheckoutBtn(){
        buttonCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsActivity.this,CheckoutActivity.class);
                intent.putExtra("goodses",(Serializable)goodsListFragment.getGoodses());
                intent.putExtra("goodsCart",(Serializable)goodsCart);
                intent.putExtra("allPrice",allPrice);
                intent.putExtra("bID",bID);
                intent.putExtra("bName",bName);
                GoodsActivity.this.startActivity(intent);
            }
        });
    }
    public void cartPopWindow() {
        buttonCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindow();

                if (goodsListFragment.getGoodses() != null && goodsListFragment.getGoodses().size() > 0
                        && goodsCart.size() > 0) {
                    cartAdapter = new MyCartAdapter(goodsListFragment.getGoodses(), goodsCart, getLayoutInflater(), handler);
                    listCart.setAdapter(cartAdapter);
                }
                //popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
                popupWindow.showAsDropDown(ll2, -500, 0);


            }
        });
    }

    public void initPopCart() {

        cartPopWindow();

        final View popView = getLayoutInflater().inflate(R.layout.activity_popcart, null);
        popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, 500, true);

        initCartView(popView);


    }

    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopCart();
        }
    }

    private void initCartView(final View popView) {

        //设置边缘触摸返回
        //popupWindow.setAnimationStyle(R.style.AnimationFade);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popView != null && popView.isShown()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        //设置清空按钮

        Button clear = (Button) popView.findViewById(R.id.btnClearCart);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsCart.clear();
                Message msg = new Message();
                msg.what = 5;
                handler.sendMessage(msg);
            }
        });
        //设置list
        listCart = (ListView) popView.findViewById(R.id.listCart);

    }


}
